package com.example.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.example.dto.PersonDTO;
import com.example.entity.Person;
import com.example.service.PersonService;
import com.example.vo.PersonOfCarVO;
import com.example.vo.PersonVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 人相关的业务
 * @author taoshen
 * @create 2022/1/23
 */
@RestController
@RequestMapping("person")
public class PersonController {
    @Autowired
    private PersonService personService;
    /**
     * 查询所有person
     */
    @GetMapping("findAll")
    public Map<String, Object> findAll(
            @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> map = MapUtil.newHashMap();

        try {
            List<Person> personList = personService.findAll();

            List<PersonVO> personVOList = CollUtil.newArrayList();

            personList.forEach(person -> {
                PersonVO personVO = new PersonVO();
                BeanUtil.copyProperties(person, personVO, "create_time", "update_time", "del_flag");
                personVOList.add(personVO);
            });

            map.put("msg", "查询成功");
            map.put("code", 200);
            map.put("data", personVOList);
        } catch (Exception exception) {
            map.put("msg", exception.getMessage());
            map.put("code", 500);
        }

        return map;
    }

    /**
     * 查询某个人的车子名字
     *
     * 返回体：
     *  人名
     *  集合：车品牌
     */
    @GetMapping("findOnePersonCarBrands")
    public Map<String, Object> findOnePersonCarBrands(@RequestParam(required = true) String name) {
        Map<String, Object> map = MapUtil.newHashMap();

        try {
            PersonOfCarVO vo = personService.findOnePersonCarBrands(name);

            map.put("msg", "查询成功");
            map.put("code", 200);
            map.put("data", vo);
        } catch (Exception exception) {
            map.put("msg", exception.getMessage());
            map.put("code", 500);
        }

        return map;
    }

    /**
     * {
     *  "id": 2,
     *  "name": "wangwu",
     *  "age": 12
     * }
     */
    @PostMapping("insertOnePerson")
    public Map<String, Object> insertOnePerson(@RequestBody PersonDTO personDTO) {
        Map<String, Object> map = MapUtil.newHashMap();

        try {
            personService.insertOnePerson(personDTO);
            map.put("msg", "新增成功");
            map.put("code", 200);
        } catch (Exception exception) {
            map.put("msg", exception.getMessage());
            map.put("code", 500);
        }

        return map;
    }



}
